package _binary_search;

import java.util.ArrayList;
import java.util.List;

/**
 * 658. 找到 K 个最接近的元素
 */
public class No658 {
    public List<Integer> findClosestElements(int[] arr, int k, int x) {
        int n = arr.length;
        int left = 0, right = n - 1;
        while (left <= right) {
            int mid = left + (right - left >> 1);
            if (arr[mid] < x) left = mid + 1;
            else right = mid - 1;
        }
        List<Integer> list = new ArrayList<>();
        right = Math.min(n - 1, left) <= 0 ? 1 : Math.min(n - 1, left);
        left = right - 1;
        while (k-- > 0) {
            if (right >= n || (left >= 0 && Math.abs(arr[left] - x) <= Math.abs(arr[right] - x))) left--;
            else right++;
        }
        for (left = left + 1; left < right; left++) {
            list.add(arr[left]);
        }
        return list;
    }
}
